package com.train.monitor;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 容器：缓冲区
 * */
public class SyncContainer {
    private List<Goods> list = new CopyOnWriteArrayList<>();
    // 生产者放入
    public synchronized void push(Goods goods) throws InterruptedException {
       // 如果容器满了(假设容器拥有10个元素则为满)，等待消费者消费
       if (list.size() == 10)
           this.wait();
       // 如果容器未满，放入商品
       list.add(goods);
       // 容器有商品了，通知消费者线程消费
       String threadName = Thread.currentThread().getName();
       System.out.println(threadName+"生产者："+goods.getGoodsName()+" 价格："+goods.getPrice());
       this.notifyAll();
    }
    // 消费者消费
    public synchronized void pop() throws InterruptedException {
       //如果容器为空，等待生产者生产
       if (list.size() == 0)
           this.wait();
       //如果容器不为空，则消费
       Goods goods = list.get(list.size() - 1);
       list.remove(goods);
       String threadName = Thread.currentThread().getName();
       System.out.println(threadName+"消费者："+goods.getGoodsName()+" 价格："+goods.getPrice());
       // 没有商品了，通知生产者线程生产
       this.notifyAll();
    }
}
